package com.jie.other.jetpack.paging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.blankj.utilcode.util.Utils
import com.jie.other.jetpack.paging.indb.DBRemoteMediator
import com.jie.other.jetpack.paging.inhttp.GithubService
import com.jie.other.jetpack.paging.inhttp.HttpPagingSource
import com.jie.other.jetpack.room.AppDataBase

class PagingViewModel(private val mDataFromHttp : Boolean = false) : ViewModel() {

    private val pagingFlow by lazy {
        if (mDataFromHttp) {
            httpFlow()
        } else {
            dbFlow()
        }
        .cachedIn(viewModelScope)
    }

    /**
     * 直接从服务器读取数据
     */
    private fun httpFlow() = Pager(
        config = PagingConfig(
            pageSize = HttpPagingSource.NETWORK_PAGE_SIZE,
            prefetchDistance = 1,
            enablePlaceholders = false,
//             initialLoadSize = 10,
        )
    ) {
        HttpPagingSource(GithubService.create())
    }.flow

    /**
     * 从数据库读取数据
     */
    @OptIn(ExperimentalPagingApi::class)
    private fun dbFlow() = Pager(
        config = PagingConfig(
            pageSize = HttpPagingSource.NETWORK_PAGE_SIZE,
            // 从数据库读时不要设置下面这个属性,否则加载更多时可能出现页面跳动的情况
//            prefetchDistance = 1,
        ),
        remoteMediator = DBRemoteMediator(mDataBase, mGithubService)
    ) {
        mRepoDao.selectAll()
    }.flow

    fun getList() = pagingFlow

    /**
     * 数据库
     */
    private val mDataBase = AppDataBase.getDataBase(Utils.getApp())

    /**
     * 查询dao
     */
    private val mRepoDao = mDataBase.getRepoDao()

    /**
     * 网络接口API
     */
    private val mGithubService = GithubService.create()

}